package com.example.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.config.http.SessionCreationPolicy;

/**
 * Spring Security配置
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                // 启用CORS支持
                .cors(cors -> cors.and())
                // 禁用CSRF保护（对于API通常不需要）
                .csrf(csrf -> csrf.disable())
                // 配置会话管理
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                // 配置授权规则
                .authorizeHttpRequests(authz -> authz
                        // 允许所有API端点的访问
                        .requestMatchers("/api/**").permitAll()
                        // 允许静态资源访问
                        .requestMatchers("/static/**", "/public/**").permitAll()
                        // 其他请求需要认证
                        .anyRequest().authenticated())
                // 禁用默认的登录页面
                .formLogin(form -> form.disable())
                // 禁用HTTP Basic认证
                .httpBasic(basic -> basic.disable())
                // 配置X-Frame-Options，禁用frame保护以支持PDF预览
                .headers(headers -> headers
                        .frameOptions().disable());

        return http.build();
    }
}